import axios from 'axios'
import { useUserStore } from '../store/user'
import { t, getLanguage } from '../lang/index'
import { getToken } from '@/utils/auth'
import Qs from 'qs'
import { showToast } from 'vant'

// const POST_HEADER = {
//     headers: {
//         'content-type': 'application/x-www-form-urlencoded',
//     },
// };
// 创建axios实例
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // api的base_url
    timeout: 35000, // 请求超时时间
    headers: {
        'with-common-headers': true, // 是否添加公共请求头
    },
    transformRequest: [function (data) {
        if (data instanceof FormData) {
            return data
        }
        return Qs.stringify(data, { arrayFormat: 'brackets' })
    }]
})

// request拦截器
service.interceptors.request.use(config => {
    config.headers['X-Token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    config.headers['X-Requested-With'] = 'XMLHttpRequest'
    config.headers['X-Lang'] = getLanguage()

    return config
}, error => {
    // Do something with request error
    Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
    response => {
        /**
        * code为非20000是抛错 可结合自己业务进行修改
        */
        const res = response.data
        if (res.code !== 20000) {
            // Message({
            //   message: res.msg,
            //   type: 'error',
            //   duration: 5 * 1000
            // })

            if (res.code === 50003 || res.code === 50008) {
                const store = useUserStore()
                showToast(t('login.invalidLogin', store.language));
                store.fedLogOut().then(() => {
                    location.reload()
                })
            }

            return Promise.reject(res.message)
        } else {
            return response.data
        }
    },
    error => {
        // Message({
        //   message: '系统内部错误：' + error,
        //   type: 'error',
        //   duration: 5 * 1000
        // })
        return Promise.reject(error)
    }
)

export default service
